const User = ($location, http, dialog) => {
    let _user;
    let _errorCount = 0;
    let _startTimer;
    let _maxNumber = 1;
    let service = {
        get: () => {
            return _user;
        },
        request: (params) => {
            var path = $location.$$path.substring(1);
            if (['forbidden', '500', '404'].indexOf(path) == -1) {
                // 防止请求异常后路由反复跳转造成的死循环
                // 限制次数内同时限制时间内异常会终止请求
                let _endTimer = new Date().getTime();
                if (_errorCount > _maxNumber && (_endTimer - _startTimer) <= (_maxNumber + 1) * 1000) {
                    return;
                }
                return http.get({
                    name: 'login_user', 
                    params: params || {},
                    success: (data) => {
                        if (!data || !angular.isObject(data)) {
                            _errorCount++;
                            if (_errorCount == 1) {
                                _startTimer = new Date().getTime();
                            }
                            return;
                        }
                        _user = angular.extend({}, data);
                        if (_errorCount > 0) _errorCount = 0;
                    },
                    error: (data) => {
                        _errorCount++;
                        if (_errorCount == 1) {
                            _startTimer = new Date().getTime();
                        }
                        _user = null;
                    }
                });
            }
        }
    }

    return service;
}

User.$inject = ['$location', 'ui.http', 'ui.dialog'];

export default User;